package cmd_db

import (
	"fmt"
	"gitee.com/theegg/go-brick/app/boot"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"gitee.com/theegg/go-brick/database/seed/seed_partner"
	"gitee.com/theegg/go-brick/database/tables"
	"github.com/spf13/cobra"
)

var (
	dir     string
	runSeed bool
	partner string
)

var StartCmd = &cobra.Command{
	Use:          "db",
	Short:        "初始化商户数据库库, 并生成seed",
	Example:      "go-brick db -d /data/www/go-brick --seed",
	SilenceUsage: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		return run()
	},
}

func init() {
	StartCmd.PersistentFlags().StringVarP(&dir, "dir", "d", "", "启动服务，指定根目录,配置文件和storage在此目录")
	StartCmd.PersistentFlags().BoolVarP(&runSeed, "seed", "s", false, "是否生成seed")
}

func run() error {
	errBoot := boot.InitApp(dir)
	if errBoot != nil {
		return errBoot
	}

	// 获取当前环境 如果为 dev / test 删除所有数据表
	if app.GetEnv() != "prod" {
		fmt.Printf("-------------------- 开始生成表 -------------------\n")
		_, has := tables.GenPartnerTable()
		if !has {
			fmt.Printf("-------------------- 生成表失败 -------------------\n")
			return nil
		}

		if runSeed {
			fmt.Printf("-------------------- 开始执行 seed-------------------\n")
			fmt.Printf("%5s|%25s|%10s|%8s|\n", "", "Table Name", "Success", "Fail")

			seed_partner.InitPartner()

			redisOb := credis.New()
			redisOb.FlushAll()
		}

		return nil
	}

	fmt.Println("--当前环境为" + app.GetEnv() + ", 请不要在生产环境下执行数据库删表操作")
	return nil
}
